package com.newasia.management.services;/**
 * Created by mic on 2019/7/30.
 */


import com.newasia.commons.tool.exception.ValidateException;
import com.newasia.management.IManagementCategoryService;
import com.newasia.management.constants.ManagementRetCode;
import com.newasia.management.converter.ItemCatConverter;
import com.newasia.management.dal.item.entitys.ItemCat;
import com.newasia.management.dal.item.entitys.ItemCatExample;
import com.newasia.management.dal.item.entitys.ItemSpu;
import com.newasia.management.dal.item.entitys.ItemSpuExample;
import com.newasia.management.dal.item.persistence.ItemCatMapper;
import com.newasia.management.dal.item.persistence.ItemSpuMapper;
import com.newasia.management.dal.user.entitys.SysMenu;
import com.newasia.management.dal.user.entitys.SysMenuExample;
import com.newasia.management.dal.user.persistence.SysMenuMapper;
import com.newasia.management.dto.productCategory.*;
import com.newasia.management.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class ManagementCategoryImpl implements IManagementCategoryService {

    @Autowired
    ItemCatMapper itemCatMapper;

    @Autowired
    ItemCatConverter itemCatConverter;

    @Autowired
    ItemSpuMapper itemSpuMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    SysMenuMapper sysMenuMapper;


    /***********************商品分类**********************/

    /**
     * 创建商品分类
     * @param request
     * @return
     */

    @Override
    public CreateItemCatResponse createItemCat(CreateItemCatRequest request) {
        CreateItemCatResponse response =new CreateItemCatResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());



        try{
            request.requestCheck();

            clearHomepageCache();

            ItemCat itemCat=itemCatConverter.req2cat(request);

            ItemCatExample item = new ItemCatExample();
            ItemCatExample.Criteria criteria = item.createCriteria();
            criteria.andParentIdEqualTo(itemCat.getParentId());
            criteria.andCatNameEqualTo(itemCat.getCatName());

            long count = itemCatMapper.countByExample(item);
            if(count>0){
                throw new ValidateException(
                        ManagementRetCode.EXIST_ITEM_CAT_NAME .getCode(),
                        ManagementRetCode.EXIST_ITEM_CAT_NAME .getMessage()
                );
            }


            if(request.getParentId()!=0){
                ItemCat itemCat1 = itemCatMapper.selectByPrimaryKey(request.getParentId());
                if(itemCat1.getFirstId().longValue()!=0&&itemCat1.getParentId()!=0){
                    throw new ValidateException(
                            ManagementRetCode.LIMIT_THREE .getCode(),
                            ManagementRetCode.LIMIT_THREE .getMessage()
                    );
                }
                itemCat.setFirstId(itemCat1.getParentId());
            }else{
                itemCat.setFirstId((long) 0);
            }

            Date date = new Date();
            itemCat.setIsParent(true);
            itemCat.setCreateTime(date);
            itemCat.setUpdateTime(date);
            itemCatMapper.insert(itemCat);


            if(request.getParentId().longValue()!=0){
                ItemSpuExample e=new ItemSpuExample();
                e.createCriteria().andCatIdEqualTo(request.getParentId());
                ItemSpu spuItem = new ItemSpu();
                spuItem.setCatId(itemCat.getCatId());

                itemSpuMapper.updateByExampleSelective(spuItem,e);
            }



        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.createAddress occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            return response;
        }
        return response;
    }


    /**
     * 删除商品分类
     * @return
     */
    @Override
    public DeleteItemCatResponse deleteItemCat(Long catId) {
        DeleteItemCatResponse response =new DeleteItemCatResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            clearHomepageCache();

            ItemCatExample itemCat = new ItemCatExample();
            ItemCatExample.Criteria criteria = itemCat.createCriteria();
            criteria.andParentIdEqualTo(catId);
            long count = itemCatMapper.countByExample(itemCat);
            if(count>0){
                throw new ValidateException(
                        ManagementRetCode.EXIST_ITEM_CAT_ERROR .getCode(),
                        ManagementRetCode.EXIST_ITEM_CAT_ERROR .getMessage()
                );
            }

            ItemSpuExample itemSpuExample = new ItemSpuExample();
            ItemSpuExample.Criteria criteria1 = itemSpuExample.createCriteria();
            criteria1.andCatIdEqualTo(catId);
            criteria1.andStatusNotEqualTo(2);
            long count1 = itemSpuMapper.countByExample(itemSpuExample);
            if(count1>0){
                throw new ValidateException(
                        ManagementRetCode.EXIST_ITEM_Good_ERROR .getCode(),
                        ManagementRetCode.EXIST_ITEM_Good_ERROR .getMessage()
                );
            }

            itemCatMapper.deleteByPrimaryKey(catId);
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.createAddress occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            return response;
        }
        return response;
    }

    /**
     * 修改商品分类
     *
     * @param catId
     * @param request
     * @return
     */
    @Override
    public ChangeItemCatResponse changeItemCat(Long catId, ChangeItemCatRequest request) {

        ChangeItemCatResponse response =new ChangeItemCatResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{



            clearHomepageCache();
            request.requestCheck();
            request.setCatId(catId);
            ItemCat itemCat=itemCatConverter.changereq2cat(request);

            ItemCatExample item = new ItemCatExample();
            ItemCatExample.Criteria criteria = item.createCriteria();
            criteria.andParentIdEqualTo(itemCat.getParentId());
            criteria.andCatIdNotEqualTo(catId);
            criteria.andCatNameEqualTo(itemCat.getCatName());
            long count = itemCatMapper.countByExample(item);
            if(count>0){
                throw new ValidateException(
                        ManagementRetCode.EXIST_ITEM_CAT_NAME .getCode(),
                        ManagementRetCode.EXIST_ITEM_CAT_NAME .getMessage()
                );
            }

            if(request.getParentId()!=null){
                if(request.getParentId()!=0){
                    ItemCat itemCat1 = itemCatMapper.selectByPrimaryKey(request.getParentId());
                    if(itemCat1.getFirstId().longValue()!=0&&itemCat1.getParentId()!=0){
                        throw new ValidateException(
                                ManagementRetCode.LIMIT_THREE .getCode(),
                                ManagementRetCode.LIMIT_THREE .getMessage()
                        );
                    }
                    itemCat.setFirstId(itemCat1.getParentId());
                }else{
                    itemCat.setFirstId((long) 0);
                }
            }
            Date date = new Date();
            itemCat.setUpdateTime(date);
            itemCatMapper.updateByPrimaryKeySelective(itemCat);
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.createAddress occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            return response;
        }
        return response;
    }





    /**
     * 获取商品分类
     * @return List<ItemCat>
     */

    @Override
    public GetItemCatResponse getItemCat(Long parentId) {
        GetItemCatResponse response =new GetItemCatResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{

            ItemCatExample itemCat = new ItemCatExample();
            if (parentId!=null){
                ItemCatExample.Criteria criteria = itemCat.createCriteria();
                criteria.andParentIdEqualTo(parentId);
            }
            itemCat.setOrderByClause("parent_id asc,sort_order asc");

            List<ItemCat> itemCats = itemCatMapper.selectByExample(itemCat);
            List<ItemCatDto> data=new ArrayList<>();

            for (ItemCat item:itemCats) {
                if (item.getParentId().longValue() == 0 &&item.getFirstId().longValue()==0) {
                    ItemCatDto itemDto = new ItemCatDto();
                    itemDto.setCatId(item.getCatId());
                    itemDto.setParentId(item.getParentId());
                    itemDto.setFirstId(item.getFirstId());
                    itemDto.setCatName(item.getCatName());
                    itemDto.setStatus(item.getStatus());
                    itemDto.setSortOrder(item.getSortOrder());
                    itemDto.setIcon(item.getIcon());
                    itemDto.setIsParent(true);
                    itemDto.setRemark(item.getRemark());
                    List<ItemCatDto> data1 = new ArrayList<>();
                    for (ItemCat item1 : itemCats) {

                        if (item1.getParentId().longValue()!=0&&item1.getFirstId().longValue()==0&&item.getCatId().longValue() == item1.getParentId().longValue()) {
                            ItemCatDto itemDto2 = new ItemCatDto();
                            itemDto2.setCatId(item1.getCatId());
                            itemDto2.setParentId(item1.getParentId());
                            itemDto2.setFirstId(item1.getFirstId());
                            itemDto2.setCatName(item1.getCatName());
                            itemDto2.setStatus(item1.getStatus());
                            itemDto2.setSortOrder(item1.getSortOrder());
                            itemDto2.setIcon(item1.getIcon());
                            itemDto2.setIsParent(true);
                            itemDto2.setRemark(item1.getRemark());

                            List<ItemCatDto> data2 = new ArrayList<>();
                            for (ItemCat item2 : itemCats) {
                                if (item2.getParentId().longValue()!=0&&item2.getFirstId().longValue()!=0&&item1.getCatId().longValue() == item2.getParentId().longValue()) {
                                    ItemCatDto itemDto3 = new ItemCatDto();
                                    itemDto3.setCatId(item2.getCatId());
                                    itemDto3.setParentId(item2.getParentId());
                                    itemDto3.setFirstId(item2.getFirstId());
                                    itemDto3.setCatName(item2.getCatName());
                                    itemDto3.setStatus(item2.getStatus());
                                    itemDto3.setSortOrder(item2.getSortOrder());
                                    itemDto3.setIcon(item2.getIcon());
                                    itemDto3.setIsParent(true);
                                    itemDto3.setRemark(item2.getRemark());
                                    data2.add(itemDto3);
                                }

                            }
                            itemDto2.setChildren(data2);
                            data1.add(itemDto2);
                        }

                        itemDto.setChildren(data1);
                    }
                    data.add(itemDto);
                }
            }

            response.setItemCatDtos(data);
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    private void clearHomepageCache(){
        SysMenuExample ex=new SysMenuExample();
        ex.createCriteria().andStatusEqualTo(0);
        List<SysMenu> sysMenus = sysMenuMapper.selectByExample(ex);
        List<String> data=new ArrayList<>();
        for (SysMenu s:sysMenus) {
            data.add(s.getMenuId().longValue()+"");
        }
        data.add("null");
        data.add("0");

        for (String s:data) {
            StringBuilder home_page=new StringBuilder("home_page");
            StringBuilder home_page_nav=new StringBuilder("home_page_nav");

            home_page.append(":").append(s);
            home_page_nav.append(":").append(s);
            RBucket rBucket = redissonClient.getBucket(home_page.toString());
            rBucket.expire(0, TimeUnit.DAYS);

            RBucket bucket = redissonClient.getBucket(home_page_nav.toString());
            bucket.delete();
            bucket.expire(0, TimeUnit.DAYS);
        }
        RBucket product_cate=redissonClient.getBucket("product_cate");
        product_cate.expire(0, TimeUnit.DAYS);
    }


}
